package com.atguigu.myjuc.demo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 死锁演示
 */
public class DeadLockDemo {
//    private static Lock lock1 = new ReentrantLock();
//    private static Lock lock2 = new ReentrantLock();
    static Object lockA = new Object();
    static Object lockB = new Object();
    public static void main(String[] args) {

        new Thread(()->{
            synchronized (lockA){
                System.out.println(Thread.currentThread().getName()+"\t"+"持有A锁,尝试获取B锁");
                //暂停亳秒
                try { TimeUnit.MICROSECONDS.sleep(10); } catch (Exception e) { e.printStackTrace(); }
                synchronized (lockB){
                    System.out.println(Thread.currentThread().getName()+"\t"+"获取B锁");
                }
            }
        },"A").start();

        new Thread(()->{
            synchronized (lockB){
                System.out.println(Thread.currentThread().getName()+"\t"+"持有B锁,尝试获取A锁");
                //暂停亳秒
                try { TimeUnit.MICROSECONDS.sleep(10); } catch (Exception e) { e.printStackTrace(); }
                synchronized (lockA){
                    System.out.println(Thread.currentThread().getName()+"\t"+"获取A锁");
                }
            }
        },"B").start();

        /*new Thread(()->{
            lock1.lock();
            System.out.println(Thread.currentThread().getName()+"\t"+"持有A尝试获取B");

            //暂停亳秒
            try { TimeUnit.MICROSECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); }
            lock2.lock();
            System.out.println(Thread.currentThread().getName()+"\t"+"获取B");
            lock2.unlock();
            lock1.unlock();
        },"A").start();

        new Thread(()->{
            lock2.lock();
            System.out.println(Thread.currentThread().getName()+"\t"+"持有B,尝试获取A");

            //暂停亳秒
            try { TimeUnit.MICROSECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); }
            lock1.lock();
            System.out.println(Thread.currentThread().getName()+"\t"+"获取A");
            lock1.unlock();
            lock2.unlock();
        },"B").start();*/
    }
}
